#!/bin/sh
if [ -z "$1" ]; then
   exit
fi
tar xfvj "$1"
dir=`echo $(basename "$1")|sed -n 's/^\(.*_pin_[0-9]\+\)_.*\.tbz2$/\1/p'`
if [ ! -d "$dir" ]; then
   exit
fi
save_IFS=$IFS;IFS='
';traces=(`ls -1 $dir/lit/*.arch.xml.gz|sed 's/^.*\/.*\/\(pin_.*_\(.*\)_.*_linux64_\([0-9]\+\)_sde_v\(.*\)_[0-9]\+_\([0-9]\+\)\.\(.*\)\)\.arch\.xml\.gz$/\2 \3 \4 \5 \1/'`)
IFS=$save_IFS
prv_var=''
for t in "${traces[@]}"; do
   d=($t)
   cur_var=${d[2]}
   if [ -z "$prv_var" ]; then
      prv_var=$cur_var
      continue
   fi
   if [ ${#prv_var} -le ${#cur_var} ];then
      cmn_var=$prv_var
   else
      cmn_var=$cur_var
   fi
   while [ -n "$cmn_var" ]; do
      if [[ "$prv_var" == "$cmn_var"* ]] && [[ "$cur_var" == "$cmn_var"* ]]; then break; fi
      cmn_var=${cmn_var:0:$((${#cmn_var}-1))}
   done
   prv_var="$cmn_var"
done
cmn_len=${#prv_var}
files='lit: pinlit64: ami arch.xml lit procinfo.xml cmd tzcat report: pinlit64: result global.log mfp.tzcat none: baseline.txt coverage.txt coverage.sw.txt coverage.wm.txt environment.txt flow.disasm flow.s func loop mix-out.txt profile.csv pinlit64: ptov warmup.ptov address none: algn-out.txt clc-out.txt msk-out.txt'
for t in "${traces[@]}"; do
   d=($t)
   plt=${d[2]:$cmn_len}
   sfx=`echo $plt|sed -n 's/-\(avx\|fma\|sse\)\([0-9]\+\(-[0-9]\+\)\?\)\?$//p'`
   if [ -n "$sfx" ]; then plt=${plt:$((${#sfx}+1))}; fi
   plt=`echo $plt|tr [:lower:]- [:upper:].`
   isa=${plt/FMA/AVX2}
   r=`echo ${d[3]}|sed 's/^0*//'`
   trace_base=R$r.${d[0]}.$plt${sfx:+.$sfx}
   trace_dir=${2:+$2/}$isa${sfx:+.$sfx}_icl_${d[1]}_LCAT
   trace_adir=`readlink -f "$trace_dir"`
   region_dir=$trace_dir/rgn.$trace_base
   if [ -d $region_dir ]; then
      echo;echo Warning: Directory $region_dir already exists, skipping...;echo;continue
   fi
   mkdir -p $region_dir
   wrk_dir=''
   wrk_nm=''
   for f in $files; do
      if [ $f == lit: ]; then
         wrk_dir=$dir/lit/${d[4]}.; continue
      elif [ $f == report: ]; then
         wrk_dir=$dir/report/${d[4]}.; continue
      elif [ $f == pinlit64: ]; then
         wrk_nm=pinlit64.; continue
      elif [ $f == none: ]; then
         wrk_nm=''; continue
      elif [ $f == func ]; then
         f=func.$plt.s
      elif [ $f == loop ]; then
         f=loop.$plt.s
      fi
      v=$f
      if [ ! -r $wrk_dir$v ]; then v=$f.gz; fi
      if [ ! -r $wrk_dir$v ]; then v='[0-9]*.'$f; fi
      if [ ! -r $wrk_dir$v ]; then v='[0-9]*.'$f.gz; fi
      if [ ! -r $wrk_dir$v ]; then continue; fi
      v=`echo $wrk_dir$v`;v=${v:${#wrk_dir}}
      mv $wrk_dir$v $region_dir/$wrk_nm$v
   done
   cur_dir="$PWD";cd $region_dir
      if [[ "$PWD" == */$region_dir ]]; then
         tar -cvj --remove-files -f $trace_adir/wlit.$trace_base.tbz2 *
      fi
   cd $cur_dir
   rmdir $region_dir
done
rmdir $dir/lit $dir/report $dir
